package com.example.gatewaydemo.filter;

import com.google.gson.Gson;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

public class ModifyRequestBodyFilter implements GlobalFilter , Ordered {
    private final Gson gson = new Gson();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpMethod method = exchange.getRequest().getMethod();
        if(method.equals(HttpMethod.POST)){
            ModifyRequestBodyGatewayFilterFactory.Config config = new ModifyRequestBodyGatewayFilterFactory.Config();
            config.setInClass(String.class);
            config.setOutClass(String.class);
            config.setRewriteFunction(new RewriteFunction() {
                @Override
                public Object apply(Object o, Object o2) {
                    ServerWebExchange serverWebExchange = (ServerWebExchange) o;
                    String oldBody = (String) o2;
                    if (exchange.getRequest().getURI().getRawPath().contains("modify-request")) {
                        Map map = gson.fromJson(oldBody, Map.class);
                        map.put("hello", "new request body insert!!");
                        return Mono.just(gson.toJson(map));
                    }
                    return Mono.just(oldBody);
                }
            });
            return new ModifyRequestBodyGatewayFilterFactory().apply(config).filter(exchange, chain);
        }
       return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
